package com.du.dumall.product.exception;

import com.du.dumall.common.exception.ExceptionEnum;
import com.du.dumall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.du.dumall.product.controller")
public class MallExceptionControllerAdvice {

    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException error){
        BindingResult bindingResult = error.getBindingResult();
        Map<String,String> map = new HashMap<>();
        bindingResult.getAllErrors().forEach(result ->{
            map.put(result.getObjectName(),result.getDefaultMessage());
        });
        return R.error(ExceptionEnum.VALUE_EXCEPTION.getCode(),ExceptionEnum.VALUE_EXCEPTION.getMessage()).put("data",map);
    }

    @ExceptionHandler(value= Throwable.class)
    public R handleException(Throwable t){
        return R.error(ExceptionEnum.NUKNOW_EXCEPTION.getCode(),ExceptionEnum.NUKNOW_EXCEPTION.getMessage()).put("data",t.getMessage());
    }


}
